from typing import Any
import numpy as np
from fastmcp import FastMCP
from fastmcp import Client # Import the client
import asyncio
import requests
from config.app_config import AppConfig as AC

class McpcFm(object):
    client = Client('http://127.0.0.1:8000/mcp/')

    def __init__(self):
        self.name = 'apps.cpm.mcp.draw_x_ys_mcpc_fm.DrawXYsMcpcFm'

    

    @staticmethod
    def upload_file(fn_ext:str, arr:bytes) -> int:
        # 准备表单数据
        files = {
            'val': ('a001', arr)
        }
        data = {
            'fn_ext': fn_ext
        }
        
        try:
            # 发送POST请求
            response = requests.post(AC.upload_file_url, files=files, data=data)
            # 检查响应
            if response.status_code == 200:
                result = response.json()
                print("文件上传成功!")
            else:
                print(f"上传失败! 状态码: {response.status_code}")
                print(f"错误信息: {response.text}")
        
        except requests.exceptions.RequestException as e:
            print(f"请求失败: {str(e)}")
        finally:
            # 确保文件关闭
            print(f'Sent')
        return result

    @staticmethod
    def upload_obj(key:str, arr:np.ndarray) -> int:
        # 准备表单数据
        files = {
            'val': ('a001', arr.tobytes())
        }
        data = {
            'key': key
        }
        
        try:
            # 发送POST请求
            response = requests.post(AC.upload_obj_url, files=files, data=data)
            
            # 检查响应
            if response.status_code == 200:
                result = response.json()
                print("对象上传成功!")
            else:
                print(f"上传失败! 状态码: {response.status_code}")
                print(f"错误信息: {response.text}")
        
        except requests.exceptions.RequestException as e:
            print(f"请求失败: {str(e)}")
        finally:
            # 确保文件关闭
            print(f'Sent')
        return 0
    
    @staticmethod
    def download_file(fn:str) -> bytes:
        resp = requests.get(f'{AC.download_file_url}/{fn}')
        return resp.content
    
    @staticmethod
    def get_key_str(key:str) -> Any:
        url = f'{AC.get_key_str_url}?key={key}'
        resp = requests.get(url).json()
        print(f'resp: {resp}; {resp["val"]};')

    @staticmethod
    def get_key_obj(key:str) -> bytes:
        url = f'{AC.get_key_obj_url}?key={key}'
        resp = requests.get(url)
        return resp.content









    @staticmethod
    def call_mcp_server() -> str:
        # Run the local test function
        asyncio.run(McpcFm.test_server_locally())
        # Commented out for now, we'll focus on running the server next

    @staticmethod
    async def test_server_locally():
        # Clients are asynchronous, so use an async context manager
        async with McpcFm.client:
            # Call the 'greet' tool
            greet_result = await McpcFm.client.call_tool("greet", {"name": "FastMCP User"})
            print(f"greet result: {greet_result.structured_content["result"]}")

            # Call the 'add' tool
            add_result = await McpcFm.client.call_tool("add", {"a": 5, "b": 7})
            print(f'{add_result.structured_content["result"]};')

            # Read the 'config' resource List[{'uri', 'mimeType', 'meta', 'text'}]
            config_data = await McpcFm.client.read_resource("data://config")
            print(f"config resource: {len(config_data)}")
            for cdi in config_data:
                print(f'    # uri: {cdi.uri}; mimeType: {cdi.mimeType}; meta: {cdi.meta}; text: {cdi.text}; {type(cdi.text)};')

            # Read a user profile using the template
            user_profile = await McpcFm.client.read_resource("users://101/profile")
            print(f"User 101 profile: {len(user_profile)}")
            for upi in user_profile:
                print(f'    @ uri: {upi.uri}; mimeType: {upi.mimeType}; meta: {upi.meta}; text: {upi.text}; {type(upi.text)};')

            # Get the 'summarize' prompt structure (doesn't execute the LLM call here)
            prompt_messages = await McpcFm.client.get_prompt("summarize", {"text": "This is some text."})
            print(f"Summarize prompt structure: meta: {prompt_messages.meta}; description: {prompt_messages.description}; messages: {type(prompt_messages.messages)};")
            for m in prompt_messages.messages:
                print(f'    $ {m}; {type(m)};')

if '__main__' == __name__:
    print(f'MCP客户端 v0.0.2')
    McpcFm.call_mcp_server()
